import requests


def get_index_code(index_name):
    """
    通过腾讯财经搜索指数代码
    """
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }

    try:
        # 腾讯财经搜索API
        url = f"http://qt.gtimg.cn/q={requests.utils.quote(index_name)}"
        response = requests.get(url, headers=headers, timeout=10)
        response.encoding = 'gbk'

        # 解析返回数据
        lines = response.text.split(';')
        for line in lines:
            if 'v_' in line:
                parts = line.split('~')
                if len(parts) > 1:
                    name = parts[1]
                    code = parts[2]
                    if index_name in name:
                        return code
        return None

    except Exception as e:
        print(f"搜索失败: {e}")
        return None


# 使用示例
index_name = "沪深300"
code = get_index_code(index_name)
print(f"{index_name} 的代码是: {code}")